package com.xinting.piano.service;

import android.util.Log;

import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.xinting.piano.data.PApp;
import com.xinting.piano.data.PMelody;
import com.xinting.piano.lib.network.PNetWork;
import com.xinting.piano.lib.util.PUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by wuxinting on 15/11/10.
 * 评论相关的业务
 */
public class PCommentService {

    public static final String LOG_TAG = PApp.LOG_TAG+"_comments";
    public static final String URL_COMMENTS = "album/comments";
    public static final String KEY_COMMENTS = "comments";

    private PMelody melody;

    public PCommentService(PMelody melody) {
        this.melody = melody;
    }

    /**
     * 获取melody的count条热门评论
     * @param count 评论条数,如果为0，表示所有的评论
     * @param handleJson 回调
     * @return 是否成功
     */
    public Boolean getMelodyComments(int count, IHandleJson handleJson) {
        String url = PUtil.joinURL(PApp.URL_SERVER, URL_COMMENTS);
        Map<String, String> params = new HashMap<>();
        params.put(PMelody.KEY, melody.getId());
        params.put(PApp.KEY_COUNT, ""+count);
        PAccount.getInstance().fillTokenToParam(params);

        try {
            PNetWork.getInstance().post(url, params, new HandleCommentResult(handleJson));
        } catch (IOException e) {
            Log.e(LOG_TAG, e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 获取melody的所有评论
     */
    public Boolean getMelodyComments(IHandleJson handler) {
        return getMelodyComments(0, handler);
    }

    /**
     * 统一处理评论相关的网络返回
     */
    private class HandleCommentResult implements PNetWork.IHandleHttpResult {

        private IHandleJson handler;
        public HandleCommentResult(IHandleJson handler) {
            this.handler = handler;
        }

        @Override
        public void onRequest(Request req, IOException e) {
            Log.e(LOG_TAG, e.getMessage());
        }

        @Override
        public void onResponse(Response res) throws IOException {
            String rs = res.body().string();
            try {
                JSONObject json = new JSONObject(rs);
                if (handler != null) {
                    handler.handleJson(json);
                }
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage());
            }
        }
    }

}
